package com.ws.framework.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Strings;

public class PropertiesUtil {

    private static final Logger LOG = LoggerFactory.getLogger(PropertiesUtil.class);

    private static Map<String, String> propertiesMap = null;

    private static synchronized Map<String, String> getPropertiesMap() {
        final Properties properties = PropertiesUtil.getProperties();
        propertiesMap = new HashMap<String, String>();

        final Enumeration<?> en = properties.propertyNames();
        while (en.hasMoreElements()) {
            final String key = (String) en.nextElement();
            final String value = properties.getProperty(key);
            propertiesMap.put(key, value);
        }

        return propertiesMap;
    }

    private static Properties getProperties() {
        final Properties properties = new Properties();
        final InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream("dynamic_code.properties");

        try {
            properties.load(inputStream);
        } catch (IOException e) {
            LOG.error("method call: setting.properties was not found.", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOG.error("method call: setting.properties was not found.", e);
                }
            }
        }
        return properties;
    }

    public static String getValue(final String key) {
        if (Strings.isNullOrEmpty(key) || Strings.isNullOrEmpty(key.trim())) {
            return null;
        }
        if (null == propertiesMap) {
            propertiesMap = PropertiesUtil.getPropertiesMap();
        }
        return propertiesMap.get(key);
    }
}
